package com.zjw.spring.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * dynamic proxy for Calculator
 * 
 * @author zjw
 *
 */
public class DynamicProxy4Calculator {
	private ICalculator target;

	public DynamicProxy4Calculator() {
		target = new CalculatorImpl();
	}

	public ICalculator getProxy() {
		ClassLoader loader = target.getClass().getClassLoader();
		Class[] interfaces = target.getClass().getInterfaces();
		ICalculator proxy = (ICalculator) Proxy.newProxyInstance(loader,
				interfaces, new InvocationHandler() {

					@Override
					public Object invoke(Object proxy, Method method,
							Object[] args) throws Throwable {
						Object result = null;
						String methodName = method.getName();

						try {
							LogUtil.logBegin(methodName, args);// before advice
							result = method.invoke(target, args);
							LogUtil.logEnd(methodName, result);// after advice
						} catch (Exception e) {
							System.out.println("log :catched an exception [" + e + "].");// exception advice
							e.printStackTrace();
						}

						System.out.println("log : result = [ " + result + " ]");// return advice
						return result;
					}
				});
		return proxy;
	}

}
